package com.cn.wanxi.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")//一定要加斜杠
public class RegisterServlet extends HttpServlet {
    //    doget/dopost的区别?
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//       1. 在这里需要拿到前端传递到后台的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String birthday = req.getParameter("birthday");
        String hobby = req.getParameter("hobby");

//       2. 封装到user对象
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setPhone(phone);
        userModel.setSex(sex);
        userModel.setHobby(hobby);
        userModel.setBirthday(birthday);
//        3.调用服务逻辑层
        UserService userService = new UserServiceImpl();
//        4.接受返回数据
        String result = userService.add(userModel);
//        返回字符串后需要将结果返回到页面
//        需要封装一个对象到前端
//        ResultModel resultModel = new ResultModel();
//        resultModel.setMessage(result);
//        resp.getWriter().println(resultModel);//谁调用，谁 接受
//        5.返回给页面
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        resp.getWriter().println(jsonObject);

    }
}
